package com.zjitc.bookshop39.service.impl;

import com.zjitc.bookshop39.entity.LoginUser;
import com.zjitc.bookshop39.entity.User;
import com.zjitc.bookshop39.service.UserService;
import com.zjitc.bookshop39.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Override
    public String login(User user) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authentication = authenticationManager.authenticate(token);
        if (authentication==null) {
            return "登录失败";
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 将用户权限添加到JWT中
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", loginUser.getUsername());
        
        // 提取权限列表
        List<String> authorities = loginUser.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        claims.put("authorities", authorities);
        
        return JwtUtil.generateToken(claims);
    }
}
